# -*- coding: utf-8 -*-
# @Time : 2022/3/3 14:26
# @Author : Administrator
# @Email : simple_days@qq.com
# @File : voc2yolo.py
# @Project : meAi
# ©Copyright : 中国电建集团透平科技有限公司版权所有
import os
import xml.etree.ElementTree as ET
from pathlib import Path
from loguru import logger

# 柿子、山竹
classes = ["persimmon", "mangosteen"]


# 将x1, y1, x2, y2转换成yolov5所需要的x, y, w, h格式 归一化
def xyxy2xywh(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = round((box[0] + box[2]) / 2 * dw, 4)
    y = round((box[1] + box[3]) / 2 * dh, 4)
    w = round((box[2] - box[0]) * dw, 4)
    h = round((box[3] - box[1]) * dh, 4)
    return (x, y, w, h)  # 返回的都是标准化后的值


def parse_voc(voc_file):
    # 开始解析xml文件
    tree = ET.parse(voc_file)
    root = tree.getroot()
    size = root.find('size')  # 图片的shape值
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        # 将名称转换为id下标
        cls_id = classes.index(cls)
        # 获取整个bounding box框
        bndbox = obj.find('bndbox')
        # xml给出的是x1, y1, x2, y2
        box = [float(bndbox.find('xmin').text), float(bndbox.find('ymin').text), float(bndbox.find('xmax').text),
               float(bndbox.find('ymax').text)]

        # 将x1, y1, x2, y2转换成yolov5所需要的x_center, y_center, w, h格式
        bbox = xyxy2xywh((w, h), box)
        # 写入目标文件中，格式为 id x y w h
        # out_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')
        return cls_id, bbox


def voc2yolov5(path_text):
    pathList = [Path(path_text), ]
    # assert path.is_dir(), logger.error(f'{path_text}不是文件夹')
    while pathList:
        path = pathList.pop()
        for item in path.iterdir():
            logger.info(item.name)
            if item.is_dir():
                pathList.append(item)
            if item.is_file() and item.suffix == '.xml':
                logger.info(parse_voc(item))
                cls_id, bbox = parse_voc(item)
                outfile = item.parent.parent / 'yoloAnnotation' / (item.stem + '.txt')
                with open(outfile, 'w') as out_file:
                    out_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')


if __name__ == '__main__':
    path = './Sources'
    voc2yolov5(path)
